package tt.dz.appserver.mvc.controller;

import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import tt.dz.appserver.dao.base.RedisCacheDao;
import tt.dz.appserver.entity.model.ResultMappingEntity;
import tt.dz.appserver.service.business.ChargeService;
import tt.dz.appserver.service.business.FundService;
import tt.dz.appserver.util.Result;
import tt.dz.appserver.util.date.DateUtil;
import tt.dz.appserver.util.enums.Response;

/**
 * 充电信息控制
 * 
 * @author xielf
 *
 */
@RestController
@RequestMapping("/charge")
@Scope(value = "prototype")
public class ChargeController {

	/** 日志 */
	private static final Logger LOG = Logger.getLogger("ChargeController:");
	@Autowired
	HttpServletRequest request;

	@Resource
	private ChargeService chargeService;
	@Resource
	private FundService fundService;
	@Resource
	RedisCacheDao redisCacheDao;
	/**
	 * 开启充电
	 * 
	 * @param userCard
	 * @param chargerId
	 * @param chargePlugNo
	 *            插头号
	 * @return
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@RequestMapping(value = "/openCharge", produces = { "application/json;charset=utf-8" }, method = RequestMethod.POST)
	public String startCharge(@RequestParam String userCard, @RequestParam(value = "chargerId") String chargerId,
			@RequestParam(value = "chargerPlugNo") String chargerPlugNo,HttpSession httpSession) {

		ResultMappingEntity resultMappingEntity = null;
		LOG.info("openCharge =================================" + userCard + "    " + chargerId);

		/*
		 * StackTraceElement[] ss = Thread.currentThread().getStackTrace();
		 * for(StackTraceElement s : ss) LOG.info(s);
		 */

		try {
			// pengyu add 20180530 检查是否有未支付的订单
			String userId = null;
			userId = UserController.userIdCardMap.get("cardNo_"+userCard);
			LOG.info("userIdCardMap 中 的 userId 为 " + userId);		
			if(StringUtils.isBlank(userId)) {
				userId = redisCacheDao.getByKey("cardNo_"+userCard);	
			}
//			String userId1 = redisCacheDao.getByKey("cardNo_"+userCard);	
//			LOG.info("redisCacheDao 中 的 userId 为 " + userId1);	
			
			if (StringUtils.isNotBlank(userId)) {
				boolean flag = fundService.isHaveNeedPayOrders(userId);
				if(flag) {//存在未支付的订单
					resultMappingEntity = Result.responseBody(Response.BESPEAKRESULTEXISTNOTPAYORDER.getCode(), Response.BESPEAKRESULTEXISTNOTPAYORDER.getMsg());
					return resultMappingEntity.toString();
				}
			}	
		

			// 开启充电
			JSONObject resultJsonObject = chargeService.startCharge(userCard, chargerId, chargerPlugNo);

			String code = resultJsonObject.getString("code");
			String msg = resultJsonObject.getString("msg");

			if (Response.SUCCESS.getCode().equals(code)) {
				resultJsonObject.remove("code");
				resultJsonObject.remove("msg");
				resultMappingEntity = Result.responseBody(code, msg, resultJsonObject);
			} else {
				resultMappingEntity = Result.responseBody(code, msg);
			}
		} catch (Exception e) {
			e.printStackTrace();
			resultMappingEntity = Result.responseBody(Response.RUNTIME_ERROR.getCode(), Response.RUNTIME_ERROR.getMsg(),
					e.getMessage());
		}
		return resultMappingEntity.toString();
	}

	/**
	 * 扫码充电
	 * 
	 * @param userCard
	 * @param chargerId
	 * @param chargePlugNo
	 *            插头号
	 * @return
	 */
	@RequestMapping(value = "/scanCharge", produces = { "application/json;charset=utf-8" }, method = RequestMethod.POST)
	public String scanCharge(@RequestParam String userCard, @RequestParam(value = "qrCode") String qrCode,
			@RequestParam(value = "chargerPlugNo") String chargerPlugNo,HttpSession httpSession) {

		LOG.info(
				"扫码充电Contr date" + DateUtil.getDateTimeLong() + " qrCode=" + qrCode + "chargerPlugNo=" + chargerPlugNo);
		ResultMappingEntity resultMappingEntity = null;

		try {
			
			// pengyu add 20180530 检查是否有未支付的订单
			String userId = null;
			
			userId = UserController.userIdCardMap.get("cardNo_"+userCard);
			LOG.info("userIdCardMap 中 的 userId 为 " + userId);		
			if(StringUtils.isBlank(userId)) {
				userId = redisCacheDao.getByKey("cardNo_"+userCard);	
				LOG.info("redisCacheDao 中 的 userId0 为 " + userId);
			}
//			String userId1 = redisCacheDao.getByKey("cardNo_"+userCard);	
//			LOG.info("redisCacheDao 中 的 userId1 为 " + userId1);	
		
//			if (StringUtils.isNotBlank(userId)) {
//				JSONObject resultJSONObject = fundService.orderList(userId, "1", null, "1");// 可以尝试优化，有时间再说
//				String code0 = resultJSONObject.getString("code");
//				String msg0 = resultJSONObject.getString("msg");
//				if (Response.SUCCESS.getCode().equals(code0)) {
//					resultJSONObject.remove("code");
//					resultJSONObject.remove("msg");
//					// resultMappingEntity = Result.responseBody(code0, msg0,
//					// resultJSONObject.getJSONArray("fundList"));
//					JSONArray array = resultJSONObject.getJSONArray("fundList");
//					if(array!=null){
//						LOG.info("array.size():"+array.size());	
//					}
//					
//					for (int i = 0; i < array.size(); i++) {
//						String jsonTemp = array.get(i).toString();
//						LOG.info("jsonTemp = "+jsonTemp);
//						Object json02 = JSONObject.parse(jsonTemp);
//						Map<String, Object> jsonmap02 = (Map) json02;
//						String status = jsonmap02.get("status").toString();
//						LOG.info("status = "+status);
//						if ("0".equals(status)) {
//							resultMappingEntity = Result.responseBody(Response.BESPEAKRESULTEXISTNOTPAYORDER.getCode(),
//									Response.BESPEAKRESULTEXISTNOTPAYORDER.getMsg());
//							return resultMappingEntity.toString();
//						}
//					}
//
//					// String resultMappingEntityStr = resultMappingEntity.toString();
//					// Log.info(resultMappingEntityStr);
//					// if(resultMappingEntityStr.contains("\"status\": \"0\"")){
//					// resultMappingEntity =
//					// Result.responseBody(Response.BESPEAKRESULTEXISTNOTPAYORDER.getCode(),Response.BESPEAKRESULTEXISTNOTPAYORDER.getMsg());
//					// return resultMappingEntity.toString();
//					// }
//				}
//			}
			
			if (StringUtils.isNotBlank(userId)) {
				boolean flag = fundService.isHaveNeedPayOrders(userId);
				if(flag) {//存在未支付的订单
					LOG.info("存在未支付的订单py");
					resultMappingEntity = Result.responseBody(Response.BESPEAKRESULTEXISTNOTPAYORDER.getCode(), Response.BESPEAKRESULTEXISTNOTPAYORDER.getMsg());
					return resultMappingEntity.toString();
				}
			}
			
			
			
			JSONObject resultJsonObject = chargeService.scanCharge(userCard, qrCode, chargerPlugNo);

			String code = resultJsonObject.getString("code");
			String msg = resultJsonObject.getString("msg");

			if (Response.SUCCESS.getCode().equals(code)) {
				resultJsonObject.remove("code");
				resultJsonObject.remove("msg");
				resultMappingEntity = Result.responseBody(code, msg, resultJsonObject);
			} else {
				resultMappingEntity = Result.responseBody(code, msg);
			}
		} catch (Exception e) {
			e.printStackTrace();
			resultMappingEntity = Result.responseBody(Response.RUNTIME_ERROR.getCode(), Response.RUNTIME_ERROR.getMsg(),
					e.getMessage());
		}
		return resultMappingEntity.toString();
	}

	/**
	 * 关闭充电
	 * 
	 * @param chargeSn
	 * @return
	 */
	@RequestMapping(value = "/closeCharge", produces = { "application/json;charset=utf-8" }, method = RequestMethod.PUT)
	public String closeCharge(@RequestParam(value="chargeSn",required=true) String chargeSn) {

		ResultMappingEntity resultMappingEntity = null;

		try {

			JSONObject resultJsonObject = chargeService.closeCharge(chargeSn);

			String code = resultJsonObject.getString("code");
			String msg = resultJsonObject.getString("msg");

			if (Response.SUCCESS.getCode().equals(code)) {
				resultJsonObject.remove("code");
				resultJsonObject.remove("msg");
				resultMappingEntity = Result.responseBody(code, msg, resultJsonObject);
			} else {
				resultMappingEntity = Result.responseBody(code, msg);
			}

		} catch (Exception e) {
			e.printStackTrace();
			resultMappingEntity = Result.responseBody(Response.RUNTIME_ERROR.getCode(), Response.RUNTIME_ERROR.getMsg(),
					e.getMessage());
		}
		return resultMappingEntity.toString();
	}

	/**
	 * 获取充电列表
	 * 
	 * @param userCard
	 * @param pageNo
	 * @return
	 */
	@RequestMapping(value = "/chargeList", produces = { "application/json;charset=utf-8" }, method = RequestMethod.GET)
	public String chargeList(@RequestParam String userCard,
			@RequestParam(value = "pageNo", defaultValue = "1") Integer pageNo) {

		ResultMappingEntity resultMappingEntity = null;

		try {

			JSONObject resultJsonObject = chargeService.chargeList(userCard, pageNo);

			String code = resultJsonObject.getString("code");
			String msg = resultJsonObject.getString("msg");

			if (Response.SUCCESS.getCode().equals(code)) {
				resultJsonObject.remove("code");
				resultJsonObject.remove("msg");
				resultMappingEntity = Result.responseBody(code, msg, resultJsonObject.get("chargeDetailVo"));
			} else {
				resultMappingEntity = Result.responseBody(code, msg);
			}
		} catch (Exception e) {
			e.printStackTrace();
			resultMappingEntity = Result.responseBody(Response.RUNTIME_ERROR.getCode(), Response.RUNTIME_ERROR.getMsg(),
					e.getMessage());
		}
		return resultMappingEntity.toString();
	}

	/**
	 * 充电记录详细
	 * 
	 * @param reservationSn
	 * @return
	 */
	@RequestMapping(value = "/chargeDetail", produces = {
			"application/json;charset=utf-8" }, method = RequestMethod.GET)
	public String chargeDetail(@RequestParam String chargeSn) {

		ResultMappingEntity resultMappingEntity = null;
		try {

			JSONObject resultJsonObject = chargeService.chargeDetail(chargeSn);

			String code = resultJsonObject.getString("code");
			String msg = resultJsonObject.getString("msg");

			if (Response.SUCCESS.getCode().equals(code)) {
				resultJsonObject.remove("code");
				resultJsonObject.remove("msg");
				resultMappingEntity = Result.responseBody(code, msg, resultJsonObject.get("chargeDetail"));
			} else {
				resultMappingEntity = Result.responseBody(code, msg);
			}

		} catch (Exception e) {
			e.printStackTrace();
			resultMappingEntity = Result.responseBody(Response.RUNTIME_ERROR.getCode(), Response.RUNTIME_ERROR.getMsg(),
					e.getMessage());
		}
		return resultMappingEntity.toString();
	}

	/**
	 * 正在进行的操作
	 * 
	 * @param userPayCard
	 * @return
	 */
	@RequestMapping(value = "/getOngoingOperation", produces = {
			"application/json;charset=utf-8" }, method = RequestMethod.GET)
	public String getOngoingOperation(@RequestParam String userCard) {

		ResultMappingEntity resultMappingEntity = null;
		try {

			JSONObject resultJsonObject = chargeService.getOngoingOperation(userCard);

			String code = resultJsonObject.getString("code");
			String msg = resultJsonObject.getString("msg");

			if (Response.SUCCESS.getCode().equals(code)) {
				resultJsonObject.remove("code");
				resultJsonObject.remove("msg");
				resultMappingEntity = Result.responseBody(code, msg, resultJsonObject.get("operation"));
			} else {
				resultMappingEntity = Result.responseBody(code, msg);
			}

		} catch (Exception e) {
			e.printStackTrace();
			resultMappingEntity = Result.responseBody(Response.RUNTIME_ERROR.getCode(), Response.RUNTIME_ERROR.getMsg(),
					e.getMessage());
		}
		return resultMappingEntity.toString();

	}

	public static void main(String[] args) {

		int a = 3;
		int b = 4;
		a = a | b;
		b = a ^ b;
		a = a ^ b;
		System.out.println(a);
		System.out.println(b);
	}
}
